package com.csx.framework.springboot.sample.mvc.exception;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author cuisongxu
 * @date 2023/8/16 周三 15:44
 */
@Component
public class CustomHandlerExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

        if(ex instanceof CustomException) {

            // 这里可以自定义自己的错误页面 ModelAndView对象
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.setStatus(HttpStatus.BAD_REQUEST);
            // 设置该参数后就能在 错误页面中通过 ${message} 表达式取到该值
            modelAndView.addObject("message", ex.getMessage());
            // 该行代码将转到 /myErrorView 处理器对异常进行处理
            modelAndView.setViewName("/myErrorView");
            return modelAndView;
        }
        // 不是 CustomException,返回null，让其他解析器继续处理
        return null;
    }
}
